<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserInfoStore } from '@/stores/userInfo'
import { submitRechargeRequest } from '@/api/user'
import { User, Coin, Star, Trophy, MagicStick, ArrowLeft } from "@element-plus/icons-vue"
import router from '@/router'

const userInfoStore = useUserInfoStore()
const userInfo = computed(() => userInfoStore.userInfo)

const form = ref({
  balance: 0,
  points: 0,
  totalConsumption: 0
})

const rechargeVisible = ref(false)
const rechargeAmount = ref(null)
const fixedAmounts = [10, 50, 100, 200]
const loading = ref(false)

// 等级配置
// 等级配置
const levelConfig = {
  1: {
    name: '银米',
    tagType: 'info',
    bgColor: '#f0f9eb',
    textColor: '#67c23a',
    icon: User
  },
  2: {
    name: '金米',
    tagType: '',
    bgColor: '#f4f4f5',
    textColor: '#909399',
    icon: Coin
  },
  3: {
    name: '白金米',
    tagType: 'warning',
    bgColor: '#fdf6ec',
    textColor: '#e6a23c',
    icon: Star
  },
  4: {
    name: '钻石米',
    tagType: '',
    bgColor: '#f0f4ff',
    textColor: '#409eff',
    icon: Trophy
  },
  5: {
    name: '至尊钻石米',
    tagType: 'danger',
    bgColor: '#fef0f0',
    textColor: '#f56c6c',
    icon: MagicStick
  }
}

// 获取当前等级配置
const currentLevelConfig = computed(() => {
  return levelConfig[userInfo.value?.levelId] || levelConfig[1]
})

onMounted(() => {
  updateFormFromUserInfo()
})

const updateFormFromUserInfo = () => {
  if (userInfo.value) {
    form.value.balance = userInfo.value.balance || 0
    form.value.points = userInfo.value.points || 0
    form.value.totalConsumption = userInfo.value.totalConsumption || 0
  }
}

const backShopping = () => {
  router.push('/shopping')
}

const openRecharge = () => {
  rechargeAmount.value = null
  rechargeVisible.value = true
}

const confirmRecharge = async () => {
  if (!rechargeAmount.value || rechargeAmount.value <= 0) {
    ElMessage.warning('请输入有效的充值金额')
    return
  }

  try {
    loading.value = true
    const res = await submitRechargeRequest(rechargeAmount.value)

    if (res.status) {
      ElMessage.success(res.data || '充值申请已提交，等待管理员审核')
      rechargeVisible.value = false
    } else {
      ElMessage.error(res.message || '充值申请提交失败')
    }
  } catch (error) {
    console.error('充值请求错误:', error)
    ElMessage.error('充值请求发生错误: ' + (error.message || error))
  } finally {
    loading.value = false
  }
}

const selectAmount = (amount) => {
  rechargeAmount.value = amount
}

onMounted(() => {
  userInfoStore.fetchUserInfo()
})

</script>

<template>
  <div class="account-container">
    <div class="header">
      <el-button type="primary" plain @click="backShopping">
        <el-icon><ArrowLeft /></el-icon>
        返回主会场
      </el-button>
      <h1 class="title">账户设置</h1>
    </div>

    <el-card class="account-card">
      <div class="card-content">
        <!-- 左侧账户信息区域 -->
        <div class="info-section">
          <div class="user-level">
            <el-tag
                :type="currentLevelConfig.tagType"
                size="large"
                :style="{
                  backgroundColor: currentLevelConfig.bgColor,
                  color: currentLevelConfig.textColor,
                  borderColor: currentLevelConfig.textColor
                }"
            >
              <el-icon class="level-icon">
                <component :is="currentLevelConfig.icon" />
              </el-icon>
              {{ currentLevelConfig.name }} (VIP{{ userInfo?.levelId || 1 }})
            </el-tag>
          </div>

          <div class="account-info">
            <el-descriptions title="账户信息" column="1" border>
              <el-descriptions-item label="账户余额">
                <div class="balance-row">
                  <span class="amount">￥{{ form.balance.toFixed(2) }}</span>
                  <el-button type="primary" size="small" @click="openRecharge">充值</el-button>
                </div>
              </el-descriptions-item>
              <el-descriptions-item label="积分">
                <span class="points">{{ form.points }} 积分</span>
              </el-descriptions-item>
              <el-descriptions-item label="累计消费">
                <span class="amount">￥{{ form.totalConsumption.toFixed(2) }}</span>
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 充值弹窗 -->
    <el-dialog
        v-model="rechargeVisible"
        title="余额充值"
        width="400px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
    >
      <div style="margin-bottom: 12px; font-weight: 500;">选择充值金额：</div>

      <el-space wrap size="large" style="width: 100%; justify-content: center; margin-bottom: 20px;">
        <el-button
            v-for="amt in fixedAmounts"
            :key="amt"
            @click="selectAmount(amt)"
            :type="rechargeAmount === amt ? 'primary' : ''"
            style="width: 80px;"
        >
          ￥{{ amt }}
        </el-button>
      </el-space>

      <div class="custom-amount">
        <span class="label">或输入自定义金额：</span>
        <el-input
            v-model.number="rechargeAmount"
            type="number"
            placeholder="输入充值金额"
            min="0.01"
            step="0.01"
            clearable
        >
          <template #prefix>￥</template>
        </el-input>
      </div>

      <div v-if="rechargeAmount > 0" class="preview">
        您将充值: <span class="amount">￥{{ rechargeAmount.toFixed(2) }}</span>
      </div>

      <template #footer>
        <el-button @click="rechargeVisible = false">取消</el-button>
        <el-button
            type="primary"
            @click="confirmRecharge"
            :loading="loading"
        >
          确认充值
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.account-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  gap: 20px;
}

.title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.account-card {
  background-image: url('@/assets/IMG_20250630_185554.png');
  background-size: cover;
  background-position: center;
  opacity: 1;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.card-content {
  display: flex;
  gap: 40px;
  padding: 24px;
}

.info-section {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.user-level {
  margin-bottom: 20px;
}

.account-info {
  background-color: rgba(255, 255, 255, 0.9);
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.balance-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.amount {
  font-weight: bold;
  color: #409eff;
}

.points {
  color: #e6a23c;
  font-weight: 500;
}

.custom-amount {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 15px;
}

.custom-amount .label {
  white-space: nowrap;
  font-size: 14px;
  color: #606266;
}

:deep(.el-input__prefix) {
  align-items: center;
  display: flex;
}

.preview {
  margin-top: 15px;
  text-align: center;
  font-size: 16px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

.preview .amount {
  font-weight: bold;
  color: #409eff;
  font-size: 18px;
}

.level-icon {
  margin-right: 6px;
  font-size: 16px;
  vertical-align: middle;
}

.user-level .el-tag {
  transition: all 0.3s;
  font-weight: 500;
  padding: 8px 12px;
  border-radius: 16px;
  display: inline-flex;
  align-items: center;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .card-content {
    flex-direction: column;
  }
}

@media (max-width: 576px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .title {
    font-size: 20px;
  }

  .card-content {
    padding: 16px;
  }
}
</style>
